package com.sun.showcase.conf.security;

import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Service;


@Service
public class SecurityAccessDecisionManager implements AccessDecisionManager{

	/**
	 * Authentication 被用户赋予的资源
	 * configAttributes 访问相应资源
	 */
	public void decide(Authentication authentication, 
			           Object object,
			           Collection<ConfigAttribute> configAttributes)
			        		   throws AccessDeniedException, InsufficientAuthenticationException {
		
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();
		
		while(iterator.hasNext()){
			
			ConfigAttribute attribute = iterator.next();
			
			String resourceId = ((SecurityConfig)attribute).getAttribute();
			
			for(GrantedAuthority auth : authentication.getAuthorities()){
				
				if(resourceId.trim().equals(auth.getAuthority().trim()))
					return;
			}
		}
		
		throw new AccessDeniedException("无访问权限...");
	}

	
	/**
	 * 决定AccessDecisionManager是否可以执行传递ConfigAttribute
	 */
	public boolean supports(ConfigAttribute attribute) {

		return true;
	}

	
	/**
	 * 被安全拦截器实现调用， 
  	 *	包含安全拦截器将显示的AccessDecisionManager支持安全对象的类型
	 */
	public boolean supports(Class<?> clazz) {
	
		return true;
	}

}
